﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ScrollRectManager : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
    public ScrollRect rect;
    //存放11个text的位置信息（0,0.1，0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0）
    public List<float> textPoslist = new List<float>();
    private bool isDrag = true;

    private float targetVertical = 0;
    public static int index = 10;
    // Start is called before the first frame update
    void Start()
    {
        textTabulation();
    }

    // Update is called once per frame
    void Update()
    {
        dragTabulation();
    }

    /// <summary>
    /// 记录每个text的位置（0,0.1，0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0）
    /// </summary>
    void textTabulation()
    {
        rect = GetComponent<ScrollRect>();
        float verticalLength = rect.content.rect.height - rect.GetComponent<RectTransform>().rect.height;
        var _rectHeight = rect.GetComponent<RectTransform>().rect.height;
        for (int i = 0; i < rect.content.transform.childCount; i++)
        {
            textPoslist.Add(_rectHeight * i / verticalLength);
        }
    }

     void dragTabulation()
    {
        if (!isDrag)
        {
            rect.verticalNormalizedPosition = Mathf.Lerp(rect.verticalNormalizedPosition,targetVertical,Time.deltaTime * 4);
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        isDrag = true;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        isDrag = false;
        Vector2 pos = rect.normalizedPosition;
        float y = Mathf.Abs(pos.y - textPoslist[0]);
        for (int i = 0; i < textPoslist.Count; i++)
        {
            float temp = Mathf.Abs(pos.y - textPoslist[i]);
            if (temp < y)
            {
                y = temp;
                index = i;
            }
            if (temp == y)
            {
                y = temp;
                index = i;
            }
        }
        targetVertical = textPoslist[index];
    }
}
